package com.leunpha.mini.downloader;

import com.leunpha.mini.downloader.bean.FileBean;
import com.leunpha.mini.net.events.NetEvent;
import com.leunpha.mini.net.events.NetState;
import com.leunpha.mini.net.listener.ServerListener;
import com.leunpha.mini.utils.FileUtils;
import com.leunpha.mini.utils.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * User: zhoujingjie
 * Date: 14-6-30
 * Time: 上午10:39
 */
public class MiniDownloader extends ServerListener implements Runnable{
    private FileBean fileBean;
    public MiniDownloader(FileBean fileBean){
        this.fileBean = fileBean;
    }

    public void run(){
        try {
            _run();
        } catch (final IOException e) {
            e.printStackTrace();
            notifyListener(NetEvent.instance(NetState.ERROR, new HashMap(){{
                put("throwable",e);
                put("bean",fileBean);
            }}));
        }
    }

    /**
     * 运行。
     * @throws IOException
     */
    public void _run() throws IOException {
        URL url = new URL(fileBean.getUrl());
        /*HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
        connection.setRequestProperty("Connection","close");
        connection.setRequestProperty("Host",url.getHost());
        connection.setConnectTimeout(5*1000);
        connection.setReadTimeout(5*1000);
        //连接失败的次数
        int reconnect = 5;
        try {
            connection.connect();
        } catch (IOException e) {
            if(reconnect-->0){
                connection.connect();
            }else{
                throw new IOException(e);
            }
        }
        if(connection.getResponseCode() / 100 != 2){
            throw new IllegalStateException("code:"+connection.getResponseCode());
        }*/
        org.apache.commons.io.FileUtils.copyURLToFile(url,FileUtils.createNewFile(fileBean.getSavePath(),fileBean.getSaveName()),5000,5000);

        /*InputStream is = new BufferedInputStream(connection.getInputStream());
        OutputStream os = new FileOutputStream();
        try {
            int len;
            byte[]bytes = new byte[1024];
            while ((len=is.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
            notifyListener(NetEvent.instance(NetState.SUCCESS,fileBean));
        } finally {
            IOUtils.close(is);
            IOUtils.close(os);
            notifyListener(NetEvent.instance(NetState.END,fileBean));
        }*/
    }
}
